<template>
  <a-card :bordered="false">
    <h3>订单评价</h3>
    <OrderRatingFilter
      ref="filter"
      @onCommentReplyHandpick="handleCommentReplyHandpick"
      :btnDisabled="!!!selectedRowKeys.length"
      @onShowRatingSet="ratingSetVisible=true"
      @onExport="onExport"
      @onSearch="onSearch"
    ></OrderRatingFilter>
    <a-tabs v-model="activeKey" @change="tabChange">
      <a-tab-pane v-for="item in tabList" :tab="item.name" :key="item.status"> </a-tab-pane>
    </a-tabs>
    <s-table ref="table" bordered size="default" :rowKey="record => record.id" :columns="columns" :data="loadData" :pagination="paginationProps" :scroll="{ x: 1300 }" :rowSelection="rowSelection">
      <span slot="orderInfo" slot-scope="text, record">
        <div>订单编号：{{ record.reOrderCode }}</div>
        <div v-if="record.sourceType == 1">小程序：线下门店</div>
        <div v-else>小程序：{{ record.brandId|brandName }}</div>
        <div>评价时间：{{ record.createTime }}</div>
        <div>评价来源：{{ record.source }}</div>
        <div>用户名：{{ record.nickName }}</div>
        <div>手机号：{{ record.tel }}</div>
      </span>
      <span slot="ratingContent" slot-scope="text, record">
        <div style="display: flex;">
          <div v-if="record.handpick==1"><a-tag color="orange">精</a-tag></div>
          <div style="flex: 1;">
            <div style="word-break: break-all;">{{ record.commentContent }}</div>
            <div v-if="record.feedbackResult">{{record.feedbackSize || '尺码'}}：{{ record.feedbackResult }}</div>
            <div v-for="(item, index) in record.feedbackItemObj" :key="index">
              <div v-if="item.feedbackItemValue">{{ item.feedbackItemKey }}：{{ item.feedbackItemValue }}</div>
            </div>
            <div>描述：<a-rate :default-value="Number(record.description)" disabled /></div>
            <template v-if="record.sourceType == 1">
              <div>体验：<a-rate :default-value="Number(record.shoppingExperience)" disabled /></div>
              <div>服务：<a-rate :default-value="Number(record.shoppingServe)" disabled /></div>
            </template>
            <template v-else>
              <div>物流：<a-rate :default-value="Number(record.logistics)" disabled /></div>
              <div>服务：<a-rate :default-value="Number(record.serviceManner)" disabled /></div>
            </template>
            <div class="img-wrapper">
              <!-- <img
              class="product-img"
              @click="handlePreview('https://img.bzhz.jnbygroup.com/lgJ5YMuIHpY3iwiyEOkPy2RNc2K-')"
              src="https://picttype1.jnby.com/content/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20220510134506.png"
              alt=""
            /> -->
              <template v-if="record.commentImage">
                <img class="product-img"  v-for="(item, index) in record.commentImage.split(',')" :src="item" alt="" @click="handleShowImg(index, record.commentImage.split(','))" :key="index" />
              </template>
            </div>
          </div>
        </div>
        <div style="margin-top: 10px;word-break: break-all;" v-if="record.commentReply==1">
          <span style="color:red;">回复：</span>
          {{ record.replyContent }}
          <span style="color: #999;"> {{ record.replyCreateTime }}</span>
          <a-popconfirm
            title="确定删除此条回复?"
            @confirm="handleDeleteAnswer(record.id, record.replyId)"
          >
            <a> 删除</a>
          </a-popconfirm>
        </div>
      </span>
      <span slot="productInfo" slot-scope="text, record">
        <div class="product">
          <img class="img" v-if="record.imageUrl" :src="record.imageUrl" alt="" />
          <img class="img" v-else src="https://picttype1.jnby.com/community/goods/pl-goods.png" alt="">
          <div class="text">
            <p class="title">{{ record.goodsTitle }}</p>
            <p class="desc">{{ record.skuAttrInfo }}</p>
          </div>
        </div>
      </span>
      <span slot="status" slot-scope="text, record">
        <a-tooltip v-if="record.status == 2">
          <template #title v-if="record.auditCause">
            <div>{{ record.auditCause }}</div>
          </template>
          <a style="text-decoration: underline;">{{ record.status | status }}</a>
        </a-tooltip>
        <template v-else>{{ record.status | status }}</template>
      </span>
      <span class="action" slot="action" slot-scope="text, record">
        <!-- <a @click="handleChangeStatus(69, 3)">修改状态</a> -->
        <!-- // 0隐藏 1机审核中 2机审核不通过 3人审核中 4人审核不通过 5显示 -->
        <template v-if="record.status == 1">不可操作</template>
        <template v-if="(record.status == 5 || record.status == 0) && record.commentReply == 0">
          <a-button type="primary" size="small" @click="handleAnswer(record.id)">回复</a-button>
          <a-divider type="vertical" />
        </template>
        <template v-if="record.status == 3">
          <a @click="handleChangeStatus(record.id, 5)">审核通过</a>
          <a-divider type="vertical" />
          <a @click="handleChangeStatus(record.id, 4)">审核不通过</a>
        </template>
        <template v-if="record.status == 5 || record.status == 0">
          <a v-if="record.handpick==1" @click="handleCommentReplyHandpick(0, record.id)">取消精选</a>
          <a v-else @click="handleCommentReplyHandpick(1, record.id)">设为精选</a>
          <a-divider type="vertical" />
        </template>
        <a v-if="record.status == 5" @click="handleChangeStatus(record.id, 0)">隐藏</a>
        <a v-if="record.status == 0" @click="handleChangeStatus(record.id, 5)">显示</a>
        <a v-if="record.status == 4" @click="handleChangeStatus(record.id, 3)">重新审核</a>
      </span>
    </s-table>
    <ParagraphPic :current="imgCurrent" :visible.sync="imgVisible" :imgs="imgs"></ParagraphPic>
    <PreviewVideo :visible.sync="previewVisible" :videoUrl="videoUrl"></PreviewVideo>
    <OrderRatingModal :visible.sync="ratingSetVisible" @onRatingSet="onRatingSet"></OrderRatingModal>
    <a-modal title="回复评价" :visible="answerVisible" width="800px" @ok="handleSubmit" @cancel="answerVisible = false">
      <a-form-model ref="rulesForm" :model="form" :rules="rules">
        <a-form-model-item prop="replyComment">
          <a-textarea v-model.trim="form.replyComment" :maxLength="contentLimit" placeholder="发表你的回复~" allowClear :rows="4" />
          <div style="text-align: right;margin-top: -15px;">{{ `${contentNumber}/${contentLimit}` }}</div>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-card>
</template>
<script>
import { commentPage, commentReply, commentReplyHide, commentReplyDelete, commentReplyHandpick, commentDerive } from '@/api/micromall/sizeRecommendation'
import { STable } from '@/views/box/components'
import OrderRatingFilter from '../components/OrderRatingFilter'
import OrderRatingModal from '../components/OrderRatingModal'
import ParagraphPic from '../components/ParagraphPic'
import PreviewVideo from '../components/PreviewVideo'
import { columns } from './orderRating.js'
import { mapGetters } from 'vuex'
import { brandList } from '../components/brandList.js'
import qs from 'qs'

const tabList = [
  {
    name: '全部评价',
    status: '0'
  },
  {
    name: '用户自评',
    status: '1'
  },
  {
    name: '精选评价',
    status: '2'
  },
  {
    name: '有图/视频',
    status: '3'
  },
  {
    name: '默认评价',
    status: '4'
  },
  {
    name: '待审核',
    status: '5'
  }
]
export default {
  components: {
    OrderRatingFilter,
    STable,
    ParagraphPic,
    PreviewVideo,
    OrderRatingModal
  },
  data() {
    return {
      ratingSetVisible: false,
      id: '',
      contentLimit: 200,
      contentNumber: 0,
      form: {
        replyComment: ''
      },
      rules: {
        replyComment: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      answerVisible: false,
      previewVisible: false,
      videoUrl: '',
      imgCurrent: 0,
      imgVisible: false,
      imgs: [],
      tabList,
      activeKey: tabList[0].status,
      selectedRowKeys: [],
      selectedRows: [],
      columns,
      paginationProps: {
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
        // onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize)
      },
      statusData: {},
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const data = {
          ...this.statusData,
          ...this.queryParam,
          current: parameter.pageNo,
          size: parameter.pageSize
        }
        return commentPage(data).then(res => {
          if (res.code === 200) {
            const { records, total, size, current } = res.data
            const currentRecords = records.map(e => {
              return {
                  ...e,
                  feedbackResult: e.feedbackValue.length ? e.feedbackValue[0] : '',
                  feedbackItemObj: e.feedbackItem.map(item => {
                    for (let i in item) {
                      return {
                        feedbackItemKey: i,
                        feedbackItemValue: item[i]
                      }
                    }
                  })
                }
            })
            const data = {
              page: {
                count: total,
                pageNo: current,
                pageSize: size,
                pages: Math.ceil(total / size)
              },
              data: currentRecords
            }
            return data
          } else {
            this.$message.error(res.msg || res.message)
            const data = {
              page: {
                count: 0,
                pageNo: 0,
                pages: 0
              },
              data: []
            }
            return data
          }
        })
      }
    }
  },
  created() {
  },
  filters: {
    brandName(v) {
      const name = brandList.filter(e => e.weid == v).length ? brandList.filter(e => e.weid == v)[0].name : ''
      return name
    },
    status(status) {
      // 0隐藏 1机审核中 2机审核不通过 3人审核中 4人审核不通过 5显示
      const statusList = ['隐藏', '机审核中', '机审核不通过', '人审核中', '人审核不通过', '显示']
      return statusList[Number(status)]
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
        getCheckboxProps: record => ({
          props: {
            disabled: record.status != 5 && record.status !== '0' && record.status !== 0
          },
        })
      }
    }
  },
  mounted() {
  },
  activated() {
  },
  watch: {
    form: {
      handler: function () {
        const _this = this
        _this.contentNumber = _this.form.replyComment.length
      },
      deep: true
    }
  },
  methods: {
    // 评论设置
    onRatingSet(v) {
      console.log(v, '评论设置')
    },

    // 删除回复
    handleDeleteAnswer(commentGoodsId, id) {
      const data = {
        commentGoodsId,
        id
      }
      commentReplyDelete(data).then(res => {
        if (res.code === 200) {
          this.$refs.table.refresh()
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    // 审核/显示/隐藏
    handleChangeStatus(id, status) {
      const data = {
        id,
        status
      }
      commentReplyHide(data).then(res => {
        if (res.code === 200) {
          this.$refs.table.refresh()
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    
    // 精选、取消精选
    handleCommentReplyHandpick(type, id) {
      const data = {
        listId: id ? [id] : this.selectedRowKeys,
        type 
      }
      commentReplyHandpick(data).then(res => {
        if (res.code === 200) {
          if (this.selectedRowKeys.length) this.selectedRowKeys = []
          this.$refs.table.refresh()
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    // 回复
    handleAnswer(id) {
      console.log(id, 'idddd')
      this.id = id
      this.answerVisible = true
    },

    tabChange(activeKey) {
      this.activeKey = activeKey
      switch(activeKey) {
        case '0':
          this.statusData = {}
          break;
        case '1':
          this.statusData = {
            type: 1
          }
          break;
        case '2':
          this.statusData = {
            handpick: 1
          }
          break;
        case '3':
          this.statusData = {
            isFigure: 1
          }
          break;
        case '4':
          this.statusData = {
            type: 0
          }
          break;
        case '5':
          this.statusData = {
            status: 3
          }
          break;
      }
      this.$refs.filter.reset()
    },
    ...mapGetters(['nickname', 'avatar', 'userInfo']),
    // 回复消息
    handleSubmit() {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          this.answerVisible = false
          const data = {
            commentGoodsId: this.id,
            replyComment: this.form.replyComment,
            userId: this.userInfo().id,
            userName: this.nickname()
          }
          commentReply(data).then(res => {
            if (res.code === 200) {
              this.form.replyComment = ''
              this.$refs.table.refresh()
            } else {
              this.$message.error(res.msg)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 预览视频
    handlePreview(url) {
      this.videoUrl = url
      this.previewVisible = true
    },

    // 查看大图
    handleShowImg(index, productImgList) {
      this.imgCurrent = index
      this.imgVisible = true
      this.imgs = productImgList
    },

    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },

    // 导出评价列表
    onExport() {
      const data = {
        ...this.statusData,
        ...this.queryParam
      }
      window.location.href = commentDerive + `?${qs.stringify(data)}`
    },

    //查询
    onSearch(obj) {
      console.log(obj, 'obj')
      this.queryParam = obj
      this.$refs.table.refresh(true)
    }
  }
}
</script>
<style lang="less" scoped>
.img {
    display: block;
    margin: 0 auto;
    width: 65px;
    height: 65px;
    border: 1px dashed #f5f5f5;
    object-fit: scale-down;
  }
 /deep/.ant-table-thead > tr > th.custom-header{
    color: #fff;
    background: none;
  }
  /deep/ table tbody tr.tr:hover>td{
    background: none !important;
  }
  .product{
    display: flex;
    .img{
      width: 60px;
      height: 60px;
      object-fit: scale-down;
    }
    .text{
      flex: 1;
      margin-left: 5px;
      overflow: hidden;
      .title{
        margin: 8px 0;
        // white-space: nowrap;
        // overflow: hidden;
        // text-overflow: ellipsis;
        font-size: 12px;
      }
      .desc{
        color: #999;
        margin-bottom: 0;
        // white-space: nowrap;
        // overflow: hidden;
        // text-overflow: ellipsis;
        font-size: 12px;
      }
    }
  }
  .img-wrapper{
    display: flex;
    flex-wrap: wrap;
    .product-img{
      margin: 2px;
      width: 60px;
      height: 60px;
      object-fit: scale-down;
      border: 1px dashed #f5f5f5;
      cursor: pointer;
    }
  }
</style>
